const Commit = require('../db').Commit
const xss = require('xss')
const options = {
    whiteList: {
      a: ["href", "title", "target"],
      img:["class","draggable","alt","src","style"],
      div:["class"],
      br:["class"],
      span:['k']
    }
  };
module.exports = {
    async add (ctx, next) {
        let { content='' , tags = '', like = 0,comment = 0,images = [], parseUrl } = ctx.request.body;
        try {
            let artical = new Commit({
                content: xss(content,options),
                tags,
                images,
                parseUrl,
                like,
                comment,
                user_id: ctx._id ,
                user_name: ctx.name,
                user_avatar: ctx.avatar,
                user_company: ctx.company,
            })
            let res = await artical.save();
            if (res.id !== null ) {
                let re = await Commit.findOne({_id:res.id})
                .populate({
                    path:'user_id',
                    select: '_id avatar user_id user_name company',
                    model:'User'
                })
                ctx.body = {
                    code: 200,
                    msg: '创建成功！',
                    data: re
                }
            } else {
                ctx.body = {
                    code: 500,
                    msg: '服务器异常，请稍后再试!'
                }
            }
        }
        catch (e) {
            ctx.body = {
                code: 500,
                msg: '服务器异常，请稍后再试!'
              }
        }
    },
    async get(ctx, next) {
        let { page = 1 } = ctx.request.query;
        try {
            let res = await Commit.find({},null,{ limit: 10 , skip: 10* (page - 1) })
            .populate({
                path:'user_id',
                select: '_id avatar user_id user_name company',
                model:'User'
            })
            .sort({'_id':-1});
            if (res.length>0){
                ctx.body = {
                    code: 200, 
                    msg: '成功',
                    data: res,
                    page: page,
                }
            } else {
                ctx.body = {
                    code: 404, 
                    msg: '无记录',
                    data: res,
                    page: page,
                }
            }
        } catch (e) {
            ctx.body = {
                code: 500,
                msg: e
              }
        }
    }
}
